# -*- coding:utf-8 -*-
from datetime import datetime
from typing import List
from sqlalchemy.ext.asyncio import AsyncSession

from exceptions.exception import ServiceException
from module_admin.entity.vo.user_vo import UserInfoModel
from module_doc.dao.bg_file_category_dao import BgFileCategoryDao
from module_vip.dao.bg_download_record_dao import BgDownloadRecordDao
from module_vip.dao.bg_vip_dao import BgVipDao
from module_vip.entity.vo.bg_download_record_vo import BgDownloadRecordModel
from utils.common_util import CamelCaseUtil, export_list2excel
from module_admin.entity.vo.sys_table_vo import SysTablePageModel
from module_admin.service.sys_table_service import SysTableService
from utils.page_util import PageResponseModel
from module_doc.dao.bg_file_dao import BgFileDao
from module_doc.entity.do.bg_file_do import BgFile
from module_doc.entity.vo.bg_file_vo import BgFilePageModel, BgFileModel


class BgFileService:
    """
    用户管理模块服务层
    """

    @classmethod
    async def get_bg_file_list(cls, query_db: AsyncSession, query_object: BgFilePageModel, data_scope_sql: str|None) -> [list | PageResponseModel]:
        bg_file_list = await BgFileDao.get_bg_file_list(query_db, query_object, data_scope_sql, is_page=True)
        for file in bg_file_list.rows:
            file['fileUrl'] = None
        return bg_file_list

    @classmethod
    async def get_bg_file_by_id(cls, query_db: AsyncSession, bg_file_id: int) -> BgFileModel:
        bg_file = await  BgFileDao.get_by_id(query_db, bg_file_id)
        bg_file.file_url = None
        bg_file_model = BgFileModel(**CamelCaseUtil.transform_result(bg_file))
        return bg_file_model


    @classmethod
    async def add_bg_file(cls, query_db: AsyncSession, query_object: BgFileModel) -> BgFileModel:
        bg_file_model = await BgFileDao.add_bg_file(query_db, query_object, auto_commit=False)
        bg_file_category = await BgFileCategoryDao.get_by_id(query_db, bg_file_model.category_id)
        bg_file_category.file_count += 1
        await query_db.commit()
        return bg_file_model


    @classmethod
    async def update_bg_file(cls, query_db: AsyncSession, query_object: BgFileModel) -> BgFileModel:
        bg_file = await BgFileDao.edit_bg_file(query_db, query_object)
        bg_file_model = BgFileModel(**CamelCaseUtil.transform_result(bg_file))
        return bg_file_model


    @classmethod
    async def del_bg_file(cls, query_db: AsyncSession, bg_file_ids: List[str]):
        await BgFileDao.del_bg_file(query_db, bg_file_ids, auto_commit=False)
        for bg_file_id in bg_file_ids:
            category = await BgFileCategoryDao.get_by_id(query_db, int(bg_file_id))
            category.file_count -= 1
            await query_db.flush()
        await query_db.commit()


    @classmethod
    async def export_bg_file_list(cls, query_db: AsyncSession, query_object: BgFilePageModel, data_scope_sql) -> bytes:
        bg_file_list = await BgFileDao.get_bg_file_list(query_db, query_object, data_scope_sql, is_page=False)
        filed_list = await SysTableService.get_sys_table_list(query_db, SysTablePageModel(tableName='bg_file'), is_page=False)
        filtered_filed = sorted(filter(lambda x: x["show"] == '1', filed_list), key=lambda x: x["sequence"])
        new_data = []
        for item in bg_file_list:
            mapping_dict = {}
            for fild in filtered_filed:
                if fild["prop"] in item:
                    mapping_dict[fild["label"]] = item[fild["prop"]]
            new_data.append(mapping_dict)
        binary_data = export_list2excel(new_data)
        return binary_data

    @classmethod
    async def download_by_file_id(cls, query_db: AsyncSession, user: UserInfoModel, bg_file_id: int, ip: str) -> str:

        user_vip = await BgVipDao.get_by_user_id(query_db, user.user_id)
        today_download_times = await BgDownloadRecordDao.get_user_today_download_times(query_db, user.user_id)
        if user_vip is None or user_vip.status == '0' or user_vip.end_date < datetime.now():
            raise ServiceException(message="请先开通会员下载")
        elif today_download_times > 50:
            raise ServiceException(message="会员每日下载次数限额50")
        else:
            file = await BgFileDao.get_by_id(query_db, bg_file_id)
            file_url = file.file_url
            await BgDownloadRecordDao.add_bg_download_record(query_db, BgDownloadRecordModel(
                dept_id=user.dept_id,
                create_by=user.user_id,
                user_id=user.user_id,
                file_id=file.id,
                file_name=file.name,
                file_cover=file.cover,
                file_size=file.file_size,
                file_type=file.file_type,
                user_name=user.user_name,
                user_phone=user.phonenumber,
                download_ip=ip,
                download_status="1"
            ))

            return file_url
